package cn.wzptsoft.mall.filter;

import cn.wzptsoft.mall.pojo.LoginUser;
import cn.wzptsoft.mall.utils.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.security.sasl.AuthenticationException;
import java.io.IOException;
import java.util.Objects;

@Component
@Slf4j
public class JwtAuthenticaltionTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String path = request.getRequestURI();
        //获取token
        String token = request.getHeader("token");


        if (path.equals("/user/login") && StringUtils.hasText(token)) {
            System.out.println("登录不准带token");
            throw new RuntimeException("登录错误");
        }
        if (!StringUtils.hasText(token)) {
            System.out.println("-*-*-*-*-*-用户携带的token为null");
//            throw new RuntimeException("请先登录"); 这里不能抛出异常，不然会登录接口永远不能访问
           filterChain.doFilter(request, response);
           return;
        }

        System.out.println("-*-*-*-*-*-用户token：" + token);


        //解析token
        String id;
        try {
            Claims claims = jwtUtil.getClaimsFromToken(token);
            id = String.valueOf(claims.get("token"));
            System.out.println("-*-*-*-*-*-*-*JWt中解析的id" + id);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("token非法");
            throw new RuntimeException("出现错误，请尝试重新登录");
//            System.out.println("+--+-+-+-+-+-++-+-+-token非法");
//            filterChain.doFilter(request, response);
//            return;
        }

        //从redis中获取用户信息
        String string = null;
        try {
            string = redisTemplate.opsForValue().get(id).toString();
        } finally {
            if (Objects.isNull(string)) {
                throw new AuthenticationException("用户未登录");
            }
        }

        System.out.println("/*-//*-/*--/*-/*-*//-*"+string);

        JSONObject jsonObject = JSON.parseObject(string);
        LoginUser loginUser = jsonObject.toJavaObject(LoginUser.class);

        //存入securityContextHolder
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);

        filterChain.doFilter(request, response);
    }
}
